var BestvSearch = new Object();
var DataSourceKey = null;
var siteComboBoxlabel = null;
var IsAdmin = false;
BestvSearch.urlPrefix = "";
BestvSearch.BLANK_IMAGE_URL = BestvSearch.urlPrefix
		+ "/resources/images/default/s.gif";

// Fix extJs bug in IE9
if ((typeof Range !== "undefined") && !Range.prototype.createContextualFragment) {
	Range.prototype.createContextualFragment = function(html) {
		var frag = document.createDocumentFragment(), div = document
				.createElement("div");
		frag.appendChild(div);
		div.outerHTML = html;
		return frag;
	};
}

String.prototype.endWith = function(str) {
	if (str == null || str == "" || this.length == 0
			|| str.length > this.length)
		return false;
	if (this.substring(this.length - str.length) == str)
		return true;
	else
		return false;
	return true;
}

if (Ext.isIE) {
	document
			.write('<style type="text/css">.x-form-field-wrap .x-form-date-trigger { margin-top:-1px  } </style>');
	document
			.write('<style type="text/css">.x-form-field-wrap .x-form-trigger { margin-top:-1px  } </style>');
}

BestvSearch.glb_mainPanel = new Ext.Panel({
	border : false,
	region : 'center',
	layout : 'fit',
	margins : '0 90 0 90',
	cmargins : '5 5 5 5'
});

BestvSearch.showWaitingWin = function() {
	Ext.MessageBox.show({
		msg : TXT_common_wait_access,
		progressText : TXT_common_accessing,
		width : 380,
		wait : true,
		waitConfig : {
			interval : 200
		},
		animEl : 'mb7'
	});
};

BestvSearch.ajaxRequest = function(url, method, params, onSuccess) {
	BestvSearch.showWaitingWin();
	Ext.Ajax.request({
		url : url,
		method : method,
		params : params,
		success : function(response, options) {
			Ext.MessageBox.hide();
			var s = response.responseText;
			if (s == '[error]') {
				Ext.MessageBox.alert(TXT_common_hint, TXT_common_access_fail,
						function() {
						});
			} else if (s == '[null]') {
				Ext.MessageBox.alert(TXT_common_hint, TXT_common_relogin,
						function() {
							window.location.href = '../eni/common/logout.jsp';
						});
				return;

			} else if (s == 'No Permission') {
				Ext.MessageBox.alert(TXT_common_hint, TXT_common_no_permission,
						function() {
							window.location.href = '../eni/common/logout.jsp';
						});
				return;
			} else {
				var result = Ext.util.JSON.decode(s);
				onSuccess(result);
			}
		},
		failure : function(response, options) {
			Ext.MessageBox.hide();
			Ext.MessageBox.alert(TXT_common_hint, TXT_common_access_fail);
		}
	});
};

BestvSearch.initMainMenu = function(mainToolBar, callback, index) {
	var glb_current_user = "";
	var appMenu = new Ext.menu.Menu();
	var bindMenu = new Ext.menu.Menu();
	var programMenu = new Ext.menu.Menu();
	var searchMenu = new Ext.menu.Menu();
	var adminMenu = new Ext.menu.Menu();

	// 信息管理二级子菜单
	appMenu.add({
		id : 'addApp',
		text : '入口管理',
		disabled : true,
		handler : function() {
			location.href = '../app/entrance.htm';
		}
	}, {
		id : 'addcomm',
		text : '商品管理',
		disabled : true,
		handler : function() {
			location.href = '../app/comm.htm';
		}
	}, {
		id : 'addSpe',
		text : '专题管理',
		disabled : true,
		handler : function() {
			location.href = '../app/special.htm';
		}
	}, {
		id : 'vodManager',
		text : '节目管理',
		iconCls : 'icoEdit',
		handler : function() {
			location.href = '../app/vodManager.htm';
		}
	}, {
		id : 'personManager',
		text : '人员管理',
		iconCls : 'icoEdit',
		handler : function() {
			location.href = '../app/personManager.htm';
		}
	}, {
		id : 'TopKeywordManager',
		text : 'Top关键字管理',
		iconCls : 'icoEdit',
		handler : function() {
			location.href = '../app/topKeywordManager.htm';
		}
	});

	// 人工绑定二级子菜单.
	bindMenu.add({
		id : 'bindActivity',
		text : '人工绑定活动',
		iconCls : 'icoManual',
		disabled : true,
		handler : function() {
			location.href = '../manual/manual.htm';
		}
	}, {
		id : 'infoBind',
		text : '节目绑定',
		iconCls : 'icoEdit',
		handler : function() {
			location.href = '../manual/infoBind.htm';
		}
	});

	// 搜索统计二级子菜单
	var requestCountMenu = new Ext.menu.Menu();
	requestCountMenu.add({
		text : 'Hit请求统计',
		iconCls : 'icoAccessCountDetails',
		id : 'hitCountChart',
		handler : function() {
			location.href = '../search/hitCountChart.htm';
		}
	}, {
		text : '所有请求统计',
		iconCls : 'icoAccessCountDetails',
		id : 'allRequestCountChart',
		handler : function() {
			location.href = '../search/allRequestCountChart.htm';
		}
	});

	var leaderBoardMenu = new Ext.menu.Menu();
	leaderBoardMenu.add({
		text : '关键字排行榜',
		iconCls : 'icoLeaderboard',
		id : 'searchKeywordLeaderboard',
		handler : function() {
			location.href = '../search/searchKeywordLeaderboard.htm';
		}
	}, {
		text : '节目观看排行榜',
		iconCls : 'icoLeaderboard',
		id : 'infoHitLeaderboard',
		handler : function() {
			location.href = '../search/infoHitLeaderboard.htm';
		}
	}, {
		text : '节目提升排行榜',
		iconCls : 'icoLeaderboard',
		id : 'infoIncreaseLeaderboard',
		handler : function() {
			location.href = '../search/infoIncreaseLeaderboard.htm';
		}
	});

	var userCountMenu = new Ext.menu.Menu();
	userCountMenu.add({
		text : '用户状态统计',
		iconCls : 'icoUserStatusCount',
		id : 'userStatusCount',
		disabled : false,
		handler : function() {
			location.href = '../search/userStatusCount.htm';
		}
	}, {
		text : '新增用户统计',
		iconCls : 'icoNewUserCount',
		id : 'newUserCount',
		disabled : false,
		handler : function() {
			location.href = '../search/newUserCount.htm';
		}
	});

	searchMenu.add({
		text : '搜索预览',
		iconCls : 'icoInspect',
		id : 'searchPreview',
		disabled : true,
		handler : function() {
			location.href = '../search/searchPreview.htm';
		}
	}, {
		text : '关键字统计',
		iconCls : 'icoEdit',
		id : 'keyStat',
		handler : function() {
			location.href = '../search/keyStat.htm';
		}
	}, {
		text : '搜索排行榜',
		iconCls : 'icoLeaderboard',
		menu : leaderBoardMenu
	}, {
		text : '搜索访次统计',
		iconCls : 'icoAccessCount',
		menu : requestCountMenu
	}, {
		text : '搜索用户统计',
		iconCls : 'icoUserCount',
		menu : userCountMenu
	});

	// 暂时无用项
	programMenu.add({
		id : 'vod',
		text : 'VOD',
		handler : function() {
			location.href = '../info/vod.htm';
		}
	}, {
		id : 'tvod',
		text : 'TVOD',
		handler : function() {
			location.href = '../eni/message.htm';
		}
	}, {
		id : 'liveChannel',
		text : '直播节目',
		handler : function() {
			location.href = '../eni/finCase.htm';
		}
	});

	// 系统管理二级子菜单
	adminMenu.add({
		id : 'admin_user',
		iconCls : 'icoUser',
		text : '用户管理',
		disabled : true,
		handler : function() {
			location.href = '../admin/user.htm';
		}
	}, {
		id : 'admin_site',
		iconCls : 'icoSite',
		text : '驻地管理',
		disabled : true,
		handler : function() {
			location.href = '../admin/site.htm';
		}
	}, {
		id : 'type',
		text : '类型管理',
		iconCls : 'icoDetail',
		disabled : true,
		handler : function() {
			location.href = '../admin/type.htm';
		}
	}, {
		id : 'subType',
		text : '子类型',
		disabled : true,
		handler : function() {
			location.href = '../app/subType.htm';
		}
	}, {
		id : 'targetType',
		text : '目标类型',
		disabled : true,
		handler : function() {
			location.href = '../admin/targetType.htm';
		}
	}, {
		id : 'searchConfig',
		iconCls : 'icoFind',
		text : '搜索配置',
		disabled : true,
		handler : function() {
			location.href = '../admin/searchConfig.htm';
		}
	});

	// 导航一级菜单
	mainToolBar.add({
		text : '首页',
		id : 'indexPage',
		handler : function() {
			location.href = '../htm/index.htm';
		}
	});
	mainToolBar.add("-");
	mainToolBar.add({
		text : '信息管理',
		menu : appMenu
	});
	mainToolBar.add("-");
	mainToolBar.add({
		text : '人工绑定',
		menu : bindMenu
	});

	mainToolBar.add("-");
	mainToolBar.add({
		text : '搜索统计',
		menu : searchMenu
	});

	BestvSearch
			.ajaxRequest(
					DISPATCH_URL,
					'POST',
					'cmd=currentUser',
					function(result) {
						for ( var i = 0; i < result.roles.length; i++) {
							if (result.roles[i].name == 'HDQ') {
								this.IsAdmin = true;
								break;
							}
						}
						if (this.IsAdmin) {
							mainToolBar.add("-");
							mainToolBar.add({
								text : '系统管理',
								menu : adminMenu
							});

							appMenu.add({
								id : 'keySubject',
								iconCls : 'icoDetail',
								text : '主题词管理',
								disabled : true,
								handler : function() {
									location.href = '../app/keysubject.htm';
								}
							});
						}
						mainToolBar.add("->");
						if (this.IsAdmin) {
							var siteComBobox = BestvSearch
									.getMgmtSiteComBobox();
							mainToolBar.add(siteComboBoxlabel);
							mainToolBar.add(siteComBobox);
							mainToolBar.add("-");
						}

						glb_current_user = result.username;
						mainToolBar.addText(TXT_common_current_user
								+ glb_current_user);

						mainToolBar.add("-");
						mainToolBar.add({
							text : TXT_common_change_password,
							id : 'changePassword',
							disabled : true,
							handler : function() {
								changePasswordFormWin();
							}
						});
						mainToolBar.add("-");
						mainToolBar.add({
							text : TXT_common_logout,
							id : 'logout',
							handler : function() {
								location.href = '../eni/common/logout.jsp';
							}
						});
						mainToolBar.add("-");
						if (callback != null)
							callback.load();
						if (index == 'index') {
							var html = '<div class="m"><div class="t"></div><table><tr style="height:20px;"><td colspan="3"></td></tr><tr><td style="width:20px;"></td><td>'
									+ '<table class="adminform"><tbody>'
									+ '<tr><td valign="top">'
									+ '<div id="cpanel">';

							html += '<div style="float: left;">'
									+ '<div class="icon">'
									+ '<a href="../app/vodManager.htm">'
									+ '<img src="../images/vodManager.jpg" alt=""/><span>节目管理</span></a>'
									+ '</div>' + '</div>';
							html += '<div style="float: left;">'
									+ '<div class="icon">'
									+ '<a href="../search/hitCountChart.htm">'
									+ '<img src="../images/hitRequestCount.jpg" alt=""/><span>有效搜索统计</span></a>'
									+ '</div>' + '</div>';
							html += '<div style="float: left;">'
									+ '<div class="icon">'
									+ '<a href="../search/allRequestCountChart.htm">'
									+ '<img src="../images/allRequestCount.jpg" alt=""/><span>所有请求统计</span></a>'
									+ '</div>' + '</div>';
							html += '<div style="float: left;">'
									+ '<div class="icon">'
									+ '<a href="../search/searchKeywordLeaderboard.htm">'
									+ '<img src="../images/keywordLeaderboard.jpg" alt=""/><span>关键字排行榜</span></a>'
									+ '</div>' + '</div>';
							html += '<div style="float: left;">'
									+ '<div class="icon">'
									+ '<a href="../search/userStatusCount.htm">'
									+ '<img src="../images/userStatusScreenshot.png" alt=""/><span>用户状态统计</span></a>'
									+ '</div>' + '</div>';

							if (this.IsAdmin)
								html += '<div style="float: left;">'
										+ '<div class="icon">'
										+ '<a href="../search/keyStat.htm">'
										+ '<img src="../images/keystat.jpg" alt=""/><span>关键字统计</span></a>'
										+ '</div>' + '</div>';
							html += '</div></td></tr></tbody></table>';
							html += '</td><td style="width:20px;"></td></tr></table>';
							var p = new Ext.Panel({
								collapsible : true,
								title : '首页导航',
								border : true,
								html : html
							});
							BestvSearch.glb_mainPanel.add(p);
							BestvSearch.glb_mainPanel.doLayout();
						}
					});
};

BestvSearch.drawMainFrame = function(title, callback, index) {
	// draw header
	var headerPanel = new Ext.Panel({
		border : false,
		region : 'north',
		margins : '0 90 0 90',
		layout : 'anchor',
		height : 61,
		items : [ {
			xtype : 'box',
			el : 'header',
			border : false,
			anchor : 'none -26'
		} ]
	});

	var footerBar = new Ext.Toolbar({
		border : true,
		cls : 'bottom-toolbar',
		items : [ {
			border : true,
			frame : true,
			xtype : 'box',
			el : 'footer',
			cmargins : '5 0 0 0'
		} ]
	});
	var footerPanel = new Ext.Panel({
		region : 'south',
		layout : 'fit',
		margins : '0 90 0 90',
		baseCls : 'x-plain',
		xtype : 'box',
		height : 8,
		items : [ footerBar ]
	});

	var mainToolBar = new Ext.Toolbar({
		cls : 'top-toolbar',
		items : []
	});

	headerPanel.add(mainToolBar);
	new Ext.Viewport({
		layout : 'border',
		items : [ headerPanel, this.glb_mainPanel, footerPanel ]
	});
	document.title = title;
	if (index == 'index') {
		footerPanel.setHeight(20);
	}
	this.initMainMenu(mainToolBar, callback, index);
};

BestvSearch.isSessionTimeOut = function() {
	var conn = Ext.lib.Ajax.getConnectionObject().conn;
	var dailyActionURL = '../DispatchServlet?cmd=site&action=find&flag='
			+ Math.random();

	// Gets daily chart
	conn.open("GET", dailyActionURL, false);
	conn.send(null);
	var responseText = conn.responseText;
	if (responseText == '[null]') {
		return true;
	}
	return false;
};

BestvSearch.getMgmtSiteComBobox = function() {
	siteComboBoxlabel = this.getMgmtSiteComBoboxTitle();

	// 获取SiteComBobox默认选中的值
	BestvSearch.DataSourceKey = this.getDefaultDataSourceKey();

	var siteDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.JsonReader({
			root : 'sites',
			id : 'id',
			fields : [ {
				name : 'id'
			}, {
				name : 'name'
			}, {
				name : 'code'
			} ]
		})
	});

	siteDs.baseParams = {
		cmd : 'site',
		action : 'getMgmtSitesToJson'
	};

	siteDs.on('load', function() {
		siteCombo.setValue(BestvSearch.getDefaultDataSourceKey());
	});

	siteDs.load();

	var siteCombo = new Ext.form.ComboBox({
		name : 'siteCb',
		mode : 'local',
		forceSelection : true,
		displayField : 'name',
		valueField : 'code',
		emptyText : TXT_SITE_EXCHANGE_EMPTY,
		width : 60,
		triggerAction : 'all',
		selectOnFocus : true,
		triggerClass : 'x-form-trigger2',
		store : siteDs,
		lazyInit : false,
		editable : false
	});

	siteCombo.on('select', function(combo, record) {
		if (record.get('code') == BestvSearch.DataSourceKey)
			return;
		BestvSearch.DataSourceKey = record.get('code');
		BestvSearch.setDefaultDataSourceKey(BestvSearch.DataSourceKey);
	});

	return siteCombo;
};

BestvSearch.getDefaultDataSourceKey = function() {
	var conn = Ext.lib.Ajax.getConnectionObject().conn;
	var dailyActionURL = '../DispatchServlet?action=getDataSourceKey&flag='
			+ Math.random();
	conn.open("GET", dailyActionURL, false);
	conn.send(null);
	return conn.responseText;
};

BestvSearch.setDefaultDataSourceKey = function(dsKey) {
	var conn = Ext.lib.Ajax.getConnectionObject().conn;
	var dailyActionURL = '../DispatchServlet?action=setDataSourceKey&dataSourceKey='
			+ dsKey + '&flag=' + Math.random();
	conn.open("GET", dailyActionURL, false);
	conn.send(null);
};

BestvSearch.getMgmtSiteComBoboxTitle = function() {
	var comBoboxTitle = new Ext.form.Label({
		width : 80,
		text : TXT_SITE_EXCHANGE_TITLE
	});

	return comBoboxTitle;
};
